<template>
  <el-dialog class="app-container" :title="title"   :visible.sync="visible" top="5vh" append-to-body>
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="86px">
      <el-form-item label="姓名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading"  ref="tb" :data="customerList" @selection-change="handleSelectionChange" >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="姓名" align="center" prop="name" />
      <el-table-column label="联系人名称" align="center" prop="contactName" width="100" />
<!--      <el-table-column label="联系人电话" align="center" prop="contactTelephone" width="110" />-->
      <el-table-column label="标签" align="center" prop="label" />
      <el-table-column label="客户来源" align="center" prop="source" />
      <el-table-column label="所属地区" align="center" prop="region" />
      <el-table-column label="类别" align="center" prop="category" />
      <el-table-column label="责任人名称" align="center" prop="chargePersonName" width="100" />
      <el-table-column label="协同人名称" align="center" prop="collaboratorName" width="100"/>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <div  slot="footer" class="dialog-footer">
      <el-button type="primary" @click="handleImportCustomer" >确 定</el-button>
      <el-button @click="visible = false">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { listCustomer, getCustomer, delCustomer, addCustomer, updateCustomer } from "@/api/module/customer";
import { provinceNameList } from '@/api/module/region';
import { getDicts } from '@/api/system/dict/data';


export default {
  name: "Customer",
  data() {
    return {
      // 遮罩层
      visible: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 客户表格数据
      customerList: [],
      // 弹出层标题
      title: "选择客户",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        contactName: null,
        contactTelephone: null,
        label: null,
        source: null,
        region: null,
        category: null,
        address: null,
        createId: null,
        lossReasons: null,
        lossRemark: null,
        chargePersonId: null,
        chargePersonName: null,
        collaboratorId: null,
        collaboratorName: null,
        finalFollowTime: null,
        allocationTime: null,
        status: null,
        customerStatus: null,
        search:null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: '客户名称不能为空', trigger: 'change' }
        ],
        contactName: [
          { required: true, message: '联系人名称不能为空', trigger: 'change' }
        ],
        contactTelephone: [
          {
            required: true,
            message: '请输入正确的手机号码',
            trigger: 'blur'
          },
          {
            validator: (rule, value, callback) => {
              if (/^1[3-9]\d{9}$/.test(value) == false) {
                callback(new Error('请输入11位手机号'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
          ],
        label: [
          { required: true, message: '客户标签不能为空', trigger: 'change' }
        ],
        source: [
          { required: true, message: '客户来源不能为空', trigger: 'change' }
        ],
        regionId: [
          { required: true, message: '所属地区不能为空', trigger: 'change' }
        ],
        category: [
          { required: true, message: '客户类别不能为空', trigger: 'change' }
        ],
        chargePersonName: [
          { required: true, message: '负责人不能为空', trigger: 'change' }
        ],
      },
      regionOptions: [], //地区选择列表
      addressOptions: [], //地址选择列表
      labelOptions: [], // 标签
      sourceOptions: [], // 来源
      categoryOptions: [], // 类别
      lossReasonsOptions: [], // 流失原因
      customerStatusOptions: [], // 状态
      optionProps: {
        value: 'label',
        label: 'label',
        children: 'children'
      },
      // 是否显示用户弹出层
      openUser: false,
      customerId: "",
      customerName: "",
      contactName: "",
      contactTelephone: "",
      source:"",
      region:"",
      category:"",

    };
  },
  created() {
    this.getList();
    this.getAreaList();
    this.getLabelOptions();
    this.getSourceOptions();
    this.getCategoryOptions();
    this.getLossReasonsOptions();
    this.getCustomerStatusOptions();

  },
  methods: {
    // 显示弹框
    show() {
      this.getList();
      this.visible = true;
    },
    /** 查询客户列表 */
    getList() {
      this.loading = true;
      //查询我负责的客户
      this.queryParams.search=2;
      listCustomer(this.queryParams).then(response => {
        this.customerList = response.rows;
        // 产品类型判断
        let arr = this.customerList;
        arr.forEach(item => {
          item.label = this.getValue(this.labelOptions, item.label)
          item.source = this.getValue(this.sourceOptions, item.source)
          item.category = this.getValue(this.categoryOptions, item.category)
          item.lossReasons = this.getValue(this.lossReasonsOptions, item.lossReasons)
          item.customerStatus = this.getValue(this.customerStatusOptions, item.customerStatus)
        });
        this.customerList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getValue(arr, item) {
      for (let i = 0; i < arr.length; i++) {
        if (item === arr[i].dictValue) {
          return arr[i].dictLabel
        }
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        contactName: null,
        contactTelephone: null,
        label: null,
        source: null,
        region: null,
        category: null,
        regionId: null,
        address: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        delFlag: null,
        createId: null,
        remark: null,
        lossReasons: null,
        lossRemark: null,
        chargePersonId: null,
        chargePersonName: null,
        collaboratorId: null,
        collaboratorName: null,
        finalFollowTime: null,
        allocationTime: null,
        status: "0",
        customerStatus: "",
        addressShow:null,
        addressOptions:null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 今日新增 */
    handleQuery2() {
      this.queryParams.pageNum = 1;
      this.queryParams.search=1;
      this.getList();
    },
    /** 我负责的 */
    handleQuery3() {
      this.queryParams.pageNum = 1;
      this.queryParams.search=2;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加客户";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getCustomer(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改客户";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateCustomer(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCustomer(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除客户编号为"' + ids + '"的数据项？').then(function() {
        return delCustomer(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('module/customer/export', {
        ...this.queryParams
      }, `customer_${new Date().getTime()}.xlsx`)
    },

    //获取地区选择
    getAreaList() {
      provinceNameList().then(res => {
        this.regionOptions = res.rows;
        let arr = JSON.parse(JSON.stringify(res.rows)) //深拷贝
    /*    arr.forEach(item => {
          item.children.forEach(cItem => delete cItem.children)
        })
        debugger*/
        this.addressOptions = arr
      })
    },

    // 获取标签
    getLabelOptions() {
      getDicts('biz_label').then(response => {
        this.labelOptions = response.data
      })
    },
    // 获取来源
    getSourceOptions() {
      getDicts('biz_source').then(response => {
        this.sourceOptions = response.data
      })
    },
    // 获取类别
    getCategoryOptions() {
      getDicts('biz_category').then(response => {
        this.categoryOptions = response.data
      })
    },
    // 获取流失原因
    getLossReasonsOptions() {
      getDicts('biz_loss_reasons').then(response => {
        this.lossReasonsOptions = response.data
      })
    },
    // 获取状态
    getCustomerStatusOptions() {
      getDicts('biz_customer_status').then(response => {
        this.customerStatusOptions = response.data
      })
    },
    // 选中数据
    handleSelectionChange(selection) {
      if(selection.length>0){
        this.customerId=selection[0].id;
        this.customerName=selection[0].name;
        this.contactName=selection[0].contactName;
        this.contactTelephone=selection[0].contactTelephone;
        this.source=selection[0].source;
        this.region=selection[0].region;
        this.category=selection[0].category;
        this.address=selection[0].address
        if (selection.length > 1) {
          this.$refs.tb.clearSelection();
          this.$refs.tb.toggleRowSelection(selection.pop());
        }
      }

    },

    handleImportCustomer() {
      const customerId = this.customerId;
      if (customerId == "") {
        this.$modal.msgError("请选择用户");
        return;
      }
      this.visible = false;
      const data = {
        customerId:this.customerId,
        customerName:this.customerName,
        contactName:this.contactName,
        contactTelephone:this.contactTelephone,
        source:this.source,
        region:this.region,
        category:this.category,
        address:this.address

      }
      this.$emit("showCustomer",data);
    }


  }
};
</script>
